package _go

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func buildTree(preorder []int, inorder []int) *TreeNode {
	plen := len(preorder)
	ilen := len(inorder)
	if plen != ilen || plen <= 0 || ilen <= 0 {
		return nil
	}

	//遍历中序  可优化点  不用每次都遍历  可以放在数组中或者hash
	var root int
	for k, v := range inorder {
		if preorder[0] == v {
			root = k
			break
		}
	}

	return &TreeNode{
		Val:   preorder[0],
		Left:  buildTree(preorder[1:root+1], inorder[0:root]),
		Right: buildTree(preorder[root+1:], inorder[root+1:]),
	}
}
